export default {
  namespaced: true,
  state() {
    return {
      address: uni.getStorageSync('address') || null,
      userProfile: uni.getStorageSync('userProfile') || {
        avatarUrl:
          'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
        nickName: '微信用户'
      },
      token: uni.getStorageSync('token') || ''
    };
  },
  getters: {
    fullAddress(state) {
      if (!state.address) return '';
      const { provinceName, cityName, countyName, detailInfo } = state.address;
      return provinceName + cityName + countyName + detailInfo;
    }
  },
  mutations: {
    saveAddress(state, address) {
      state.address = address;
      uni.setStorageSync('address', address);
    },
    saveProfile(state, userProfile) {
      // 记录到 vuex 中
      state.userProfile = userProfile;
      // 存入本地
      uni.setStorageSync('userProfile', userProfile);
    },
    saveToken(state, token) {
      state.token = token;
      // 存入本地
      uni.setStorageSync('token', token);
    }
  },
  actions: {
    // 获取Token
    async getToken() {
      // 1. 通过uni.login 获取code
      const { code } = await uni.login();

      // 2. 通过 uni.getUserInfo() 获取用户信息
      const { encryptedData, iv, rawData, signature } = await uni.getUserInfo();
      // 3. 掉接口获取token
      const { data } = await uni.$http.post('/api/public/v1/users/wxlogin', {
        code,
        encryptedData,
        iv,
        rawData,
        signature
      });
      if (data.meta.status === 200) this.commit('m_user/saveToken', data.message.token);
    }
  }
};
